/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.ActionType;
import com.star.common.CommonUtil;
import com.star.common.NewsCateData;
import com.star.common.PostData;
import com.star.common.PostOnHomeData;
import com.star.common.RenderModel;
import com.star.common.UserRole;
import com.start.model.ActionModel;
import com.start.model.NewsCateModel;
import com.start.model.PostModel;
import com.start.model.PostOnHomeModel;
import com.start.model.PriorityPostModel;
import com.start.model.SessionModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminManageHomePageController extends HttpServlet{
    private static final Logger logger = Logger.getLogger(AdminManageHomePageController.class);
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if(!CommonUtil.checkSession(req, resp))
                return;
            
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminManageHomePageController.handle:" + ex.getMessage(), ex);
        }
    }
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-edit":
                content = ajaxEdit(req, resp);
                break;
            case "/edit":
                content = renderIndexPage(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";        
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.EDIT_HOME_PAGE)) {
                resp.sendRedirect("/");
                return "";
            }
            
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "managehomepage"));
            dic.setVariable("PAGE_TITLE", "Quản lý trang chủ");
                                  
            PostOnHomeModel pohModel = PostOnHomeModel.getInstance();
            List<PostOnHomeData> pohData = pohModel.getPostOnHome(0, 1);
            
            if(pohData.size() != 0)
                dic.setVariable("ID_UPDATE", pohData.get(0).getId());
            
            boolean ts1 = false, ts2 = false, ts3 = false, ts4 = false, ts5 = false, 
                    ts6 = false, ts7 = false, ts8 = false, ts9 = false, ts10 = false, 
                    ts11 = false, ts12 = false, ts13 = false, ts14 = false, ts15 = false, 
                    ts16 = false, ts17 = false, ts18 = false, ts19 = false, ts20 = false;
            String idPost1 = "", idPost2 = "", idPost3 = "", idPost4 = "", idPost5 = "", idPost6 = "", 
                    idPost7 = "", idPost8 = "", idPost9 = "", idPost10 = "", idPost11 = "", idPost12 = "", 
                    idPost13 = "", idPost14 = "", idPost15 = "", idPost16 = "", idPost17 = "", idPost18 = "", 
                    idPost19 = "", idPost20 = "", editor = "";
            long updated = 0;
            List<String> lstCateLocal = new ArrayList<>();
            List<String> lstCateInter = new ArrayList<>();
            if(!pohData.isEmpty()){
                idPost1 = pohData.get(0).getPost1();
                idPost2 = pohData.get(0).getPost2();
                idPost3 = pohData.get(0).getPost3();
                idPost4 = pohData.get(0).getPost4();
                idPost5 = pohData.get(0).getPost5();
                idPost6 = pohData.get(0).getPost6();
                idPost7 = pohData.get(0).getPost7();
                idPost8 = pohData.get(0).getPost8();
                idPost9 = pohData.get(0).getPost9();
                idPost10 = pohData.get(0).getPost10();
                idPost11 = pohData.get(0).getPost11();
                idPost12 = pohData.get(0).getPost12();
                idPost13 = pohData.get(0).getPost13();
                idPost14 = pohData.get(0).getPost14();
                idPost15 = pohData.get(0).getPost15();
                idPost16 = pohData.get(0).getPost16();
                idPost17 = pohData.get(0).getPost17();
                idPost18 = pohData.get(0).getPost18();
                idPost19 = pohData.get(0).getPost19();
                idPost20 = pohData.get(0).getPost20();
                updated = pohData.get(0).getUpdated();
                editor = pohData.get(0).getEditor();
                lstCateLocal = Arrays.asList(pohData.get(0).getLstCateLocal().split("\\s*,\\s*"));
                lstCateInter = Arrays.asList(pohData.get(0).getLstCateInter().split("\\s*,\\s*"));
            }
            
            PostModel postModel = PostModel.getInstance();
            List<PostData> lstPostLatest10 = postModel.getPost(0, 10, "", "", "", "", "1", "", "");
            if(lstPostLatest10 != null && !lstPostLatest10.isEmpty()){
                for(PostData postData : lstPostLatest10){
                    ts1 = addSection(postData, "POST_LIST1", dic, idPost1);
                    ts2 = addSection(postData, "POST_LIST2", dic, idPost2);
                    ts3 = addSection(postData, "POST_LIST3", dic, idPost3);
                    ts4 = addSection(postData, "POST_LIST4", dic, idPost4);
                    ts5 = addSection(postData, "POST_LIST5", dic, idPost5);
                    ts6 = addSection(postData, "POST_LIST6", dic, idPost6);
                    ts7 = addSection(postData, "POST_LIST7", dic, idPost7);
                    ts8 = addSection(postData, "POST_LIST8", dic, idPost8);                    
                }
            }
            
            if(ts1 == false && !pohData.isEmpty())
                addSection(idPost1, "POST_LIST1", dic);  
            if(ts2 == false && !pohData.isEmpty())
                addSection(idPost2, "POST_LIST2", dic);
            if(ts3 == false && !pohData.isEmpty())
                addSection(idPost3, "POST_LIST3", dic);
            if(ts4 == false && !pohData.isEmpty())
                addSection(idPost4, "POST_LIST4", dic);
            if(ts5 == false && !pohData.isEmpty())
                addSection(idPost5, "POST_LIST5", dic);
            if(ts6 == false && !pohData.isEmpty())
                addSection(idPost6, "POST_LIST6", dic);
            if(ts7 == false && !pohData.isEmpty())
                addSection(idPost7, "POST_LIST7", dic);
            if(ts8 == false && !pohData.isEmpty())
                addSection(idPost8, "POST_LIST8", dic);
            
            List<PostData> lstPostLatest30 = postModel.getPost(0, 30, "", "", "", "", "1", "", "");;
            if(lstPostLatest30 != null && !lstPostLatest30.isEmpty()){
                for(PostData postData : lstPostLatest30){
                    ts9 = addSection(postData, "POST_LIST9", dic, idPost9);
                    ts10 = addSection(postData, "POST_LIST10", dic, idPost10);
                    ts11 = addSection(postData, "POST_LIST11", dic, idPost11);
                    ts12 = addSection(postData, "POST_LIST12", dic, idPost12);
                    ts13 = addSection(postData, "POST_LIST13", dic, idPost13);
                    ts14 = addSection(postData, "POST_LIST14", dic, idPost14);
                    ts15 = addSection(postData, "POST_LIST15", dic, idPost15);
                    ts16 = addSection(postData, "POST_LIST16", dic, idPost16);
                    ts17 = addSection(postData, "POST_LIST17", dic, idPost17);
                    ts18 = addSection(postData, "POST_LIST18", dic, idPost18);
                    ts19 = addSection(postData, "POST_LIST19", dic, idPost19);
                    ts20 = addSection(postData, "POST_LIST20", dic, idPost20);
                }
            }
            
            if(ts9 == false && !pohData.isEmpty())
                addSection(idPost9, "POST_LIST9", dic);  
            if(ts10 == false && !pohData.isEmpty())
                addSection(idPost10, "POST_LIST10", dic);
            if(ts11 == false && !pohData.isEmpty())
                addSection(idPost11, "POST_LIST11", dic);
            if(ts12 == false && !pohData.isEmpty())
                addSection(idPost12, "POST_LIST12", dic);
            if(ts13 == false && !pohData.isEmpty())
                addSection(idPost13, "POST_LIST13", dic);
            if(ts14 == false && !pohData.isEmpty())
                addSection(idPost14, "POST_LIST14", dic);    
            if(ts15 == false && !pohData.isEmpty())
                addSection(idPost15, "POST_LIST15", dic);   
            if(ts16 == false && !pohData.isEmpty())
                addSection(idPost16, "POST_LIST16", dic);   
            if(ts17 == false && !pohData.isEmpty())
                addSection(idPost17, "POST_LIST17", dic);   
            if(ts18 == false && !pohData.isEmpty())
                addSection(idPost18, "POST_LIST18", dic);   
            if(ts19 == false && !pohData.isEmpty())
                addSection(idPost19, "POST_LIST19", dic);   
            if(ts20 == false && !pohData.isEmpty())
                addSection(idPost20, "POST_LIST20", dic);   
            
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            if(updated != 0){
                dic.showSection("UPDATE_INFO");
                Date d = new Date(updated);
                dic.setVariable("POST_UPDATED", sdf.format(d));  
                dic.setVariable("POST_EDITOR", editor);
            }
            
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            if(!lstCateLocal.isEmpty() && lstCateLocal != null){
                for(String idCate : lstCateLocal){
                    if(!idCate.equals("")){
                        NewsCateData newsCateData = newsCateModel.getNewsCateById(idCate);
                        if(newsCateData != null){
                            TemplateDataDictionary section = dic.addSection("CATE1_SELECTED");
                            section.setVariable("CATE_ID", newsCateData.getId());
                            section.setVariable("CATE_NAME", newsCateData.getName());
                        }  
                    }                                  
                }
            }
            if(!lstCateInter.isEmpty() && lstCateInter != null){
                for(String idCate : lstCateInter){
                    if(!idCate.equals("")){
                        NewsCateData newsCateData = newsCateModel.getNewsCateById(idCate);
                        if(newsCateData != null){
                            TemplateDataDictionary section = dic.addSection("CATE2_SELECTED");
                            section.setVariable("CATE_ID", newsCateData.getId());
                            section.setVariable("CATE_NAME", newsCateData.getName());
                        } 
                    }                                   
                }   
            }
                     
            
            dic.setVariable("CATE_LIST", newsCateModel.getNewsCateList());
                                    
            Template template = RenderModel.getAdminCTemplate("manage_home_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminManageHomePageController.renderIndexPage: " + ex.getMessage(), ex);
        }
        //CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }
    
    
    
                    
    private boolean addSection(PostData postData, String sectionName, TemplateDataDictionary dic, 
            String postID){
        boolean ts = false;
        TemplateDataDictionary section = dic.addSection(sectionName);
        section.setVariable("POST_ID", postData.getId());
        section.setVariable("POST_NAME", postData.getTitle()); 
        if(!postID.equals("")){
            if(postData.getId().equals(postID)){
                section.showSection("POST_SELECTED");
                ts = true;
            }                            
        }
        return ts;
    }                
    
    
    private void addSection(String postId, String sectionName, TemplateDataDictionary dic){
        PostModel postModel = PostModel.getInstance();
        PostData postData = postModel.getPostById(postId);
        if(postData != null){
            TemplateDataDictionary section = dic.addSection(sectionName);
            section.setVariable("POST_ID", postData.getId());
            section.setVariable("POST_NAME", postData.getTitle()); 
            section.showSection("POST_SELECTED");
        }
    }
    
    
    
    private String ajaxEdit(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.EDIT_HOME_PAGE)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Cập nhật nội dung thành công.";
        Map<String, String> data = new HashMap<>();
        try {    
            String id = "";
            String idPost1 = "", idPost2 = "", idPost3 = "", idPost4 = "", idPost5 = "", 
                   idPost6 = "", idPost7 = "", idPost8 = "", idPost9 = "", idPost10 = "", 
                   idPost11 = "", idPost12 = "", idPost13 = "", idPost14 = "", idPost15 = "", 
                   idPost16 = "", idPost17 = "", idPost18 = "", idPost19 = "", idPost20 = "";            
            String lstCateLocal = "";
            String lstCateInter = "";
            String select1 = "", select2 = "", select3 = "", select4 = "", select5 = "", 
                   select6 = "", select7 = "", select8 = "", select9 = "", select10 = "", 
                   select11 = "", select12 = "", select13 = "", select14 = "", select15 = "", 
                   select16 = "", select17 = "", select18 = "", select19 = "", select20 = "";    
            String textID1 = "", textID2 = "", textID3 = "", textID4 = "", textID5 = "", 
                   textID6 = "", textID7 = "", textID8 = "", textID9 = "", textID10 = "", 
                   textID11 = "", textID12 = "", textID13 = "", textID14 = "", textID15 = "", 
                   textID16 = "", textID17 = "", textID18 = "", textID19 = "", textID20 = ""; 
                                    
            
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "idupdate":
                            id = value;
                            break; 
                        case "boxid1":
                            select1 = value;
                            break;
                        case "postID1":
                            textID1 = value;
                            break;
                        case "boxid2":
                            select2 = value;
                            break;
                        case "postID2":
                            textID2 = value;
                            break;
                        case "boxid3":
                            select3 = value;
                            break;
                        case "postID3":
                            textID3 = value;
                            break;
                        case "boxid4":
                            select4 = value;
                            break;
                        case "postID4":
                            textID4 = value;
                            break;
                        case "boxid5":
                            select5 = value;
                            break;
                        case "postID5":
                            textID5 = value;
                            break;
                        case "boxid6":
                            select6 = value;
                            break;
                        case "postID6":
                            textID6 = value;
                            break;
                        case "boxid7":
                            select7 = value;
                            break;
                        case "postID7":
                            textID7 = value;
                            break;
                        case "boxid8":
                            select8 = value;
                            break;
                        case "postID8":
                            textID8 = value;
                            break;
                        case "boxid9":
                            select9 = value;
                            break;
                        case "postID9":
                            textID9 = value;
                            break;
                        case "boxid10":
                            select10 = value;
                            break;
                        case "postID10":
                            textID10 = value;
                            break;
                        case "boxid11":
                            select11 = value;
                            break;
                        case "postID11":
                            textID11 = value;
                            break;
                        case "boxid12":
                            select12 = value;
                            break;
                        case "postID12":
                            textID12 = value;
                            break;
                        case "boxid13":
                            select13 = value;
                            break;
                        case "postID13":
                            textID13 = value;
                            break;
                        case "boxid14":
                            select14 = value;
                            break;
                        case "postID14":
                            textID14 = value;
                            break;
                        case "boxid15":
                            select15 = value;
                            break;
                        case "postID15":
                            textID15 = value;
                            break;
                        case "boxid16":
                            select16 = value;
                            break;
                        case "postID16":
                            textID16 = value;
                            break;
                        case "boxid17":
                            select17 = value;
                            break;
                        case "postID17":
                            textID17 = value;
                            break;
                        case "boxid18":
                            select18 = value;
                            break;
                        case "postID18":
                            textID18 = value;
                            break;
                        case "boxid19":
                            select19 = value;
                            break;
                        case "postID19":
                            textID19 = value;
                            break;
                        case "boxid20":
                            select20 = value;
                            break;
                        case "postID20":
                            textID20 = value;
                            break;    
                        case "postListCateLocal":
                            List<String> lstResult = Arrays.asList(value.split("\\s*,\\s*"));
                            for(String cateId : lstResult){
                                if(!cateId.equals("")){
                                    NewsCateData newsCateData = newsCateModel.getNewsCateById(cateId);
                                    if(newsCateData != null){
                                        lstCateLocal += cateId + ",";
                                    }
                                }                                
                            }                            
                            break;
                        case "postListCateInter":      
                            List<String> lstResultInter = Arrays.asList(value.split("\\s*,\\s*"));
                            for(String cateId : lstResultInter){
                                if(!cateId.equals("")){
                                    NewsCateData newsCateData = newsCateModel.getNewsCateById(cateId);
                                    if(newsCateData != null){
                                        lstCateInter += cateId + ",";
                                    }
                                }                                
                            }       
                            break;                              
                    }
                }                 
            }
            
            idPost1 = testIDPost(textID1) == true ? textID1 : select1;
            idPost2 = testIDPost(textID2) == true ? textID2 : select2;
            idPost3 = testIDPost(textID3) == true ? textID3 : select3;
            idPost4 = testIDPost(textID4) == true ? textID4 : select4;
            idPost5 = testIDPost(textID5) == true ? textID5 : select5;
            idPost6 = testIDPost(textID6) == true ? textID6 : select6;
            idPost7 = testIDPost(textID7) == true ? textID7 : select7;
            idPost8 = testIDPost(textID8) == true ? textID8 : select8;
            idPost9 = testIDPost(textID9) == true ? textID9 : select9;
            idPost10 = testIDPost(textID10) == true ? textID10 : select10;
            idPost11 = testIDPost(textID11) == true ? textID11 : select11;
            idPost12 = testIDPost(textID12) == true ? textID12 : select12;
            idPost13 = testIDPost(textID13) == true ? textID13 : select13;
            idPost14 = testIDPost(textID14) == true ? textID14 : select14;
            idPost15 = testIDPost(textID15) == true ? textID15 : select15;
            idPost16 = testIDPost(textID16) == true ? textID16 : select16;
            idPost17 = testIDPost(textID17) == true ? textID17 : select17;
            idPost18 = testIDPost(textID18) == true ? textID18 : select18;
            idPost19 = testIDPost(textID19) == true ? textID19 : select19;
            idPost20 = testIDPost(textID20) == true ? textID20 : select20;
            
            if (idPost1.equalsIgnoreCase("") || idPost2.equalsIgnoreCase("") || idPost3.equalsIgnoreCase("")
                     || idPost4.equalsIgnoreCase("") || idPost5.equalsIgnoreCase("")
                     || idPost9.equalsIgnoreCase("") || idPost10.equalsIgnoreCase("")
                     || idPost15.equalsIgnoreCase("") || idPost16.equalsIgnoreCase("")
                     || idPost17.equalsIgnoreCase("") || idPost18.equalsIgnoreCase("")
                     || idPost19.equalsIgnoreCase("") || idPost20.equalsIgnoreCase("")) {
                msg = "Chưa chọn đủ tin cần thiết.";
                error = -1;
            }
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();                
                String author = sessionModel.getUserLogin(req);
                PostOnHomeModel postOnHomeModel = PostOnHomeModel.getInstance();
                if(id.equals("")){
                    PostOnHomeData postOnHomeData = new PostOnHomeData(idPost1, idPost2, idPost3, idPost4, idPost5, idPost6, 
                                                                        idPost7, idPost8, idPost9, idPost10, idPost11, idPost12, idPost13, 
                                                                        idPost14, idPost15, idPost16, idPost17, idPost18, idPost19, idPost20, 
                                                                        lstCateLocal, lstCateInter, author);
                    String idResult = postOnHomeModel.addNewPostOnHome(postOnHomeData);
                    if(!idResult.isEmpty()){
                        ActionModel actionModel = ActionModel.getInstance();                    
                        actionModel.addAction(req, author, ActionType.HOMEPAGE_EDIT, idResult, "");
                    }
                }
                else{
                    //PostOnHomeData postOnHomeEdit = postOnHomeModel.getPostOnHome(0, 1).get(0);
                    PostOnHomeData postOnHomeData = new PostOnHomeData(id, idPost1, idPost2, idPost3, idPost4, idPost5, idPost6, 
                                                                            idPost7, idPost8, idPost9, idPost10, idPost11, idPost12, idPost13, 
                                                                            idPost14, idPost15, idPost16, idPost17, idPost18, idPost19, idPost20, 
                                                                            lstCateLocal, lstCateInter, author);
                    boolean update = postOnHomeModel.updatePostOnHome(postOnHomeData);
                    if (!update) {
                        error = -1;
                        msg = "Có lỗi xảy ra.";
                    }
                    else{                                
                        ActionModel actionModel = ActionModel.getInstance();                        
                        actionModel.addAction(req, author, ActionType.HOMEPAGE_EDIT, id, "");
                    }     
                }
                //add to priority post
                PriorityPostModel priorityPostModel = PriorityPostModel.getInstance();
                priorityPostModel.updatePriorityPost(idPost1, (short)1, author);
                priorityPostModel.updatePriorityPost(idPost2, (short)2, author);
                priorityPostModel.updatePriorityPost(idPost3, (short)3, author);
                priorityPostModel.updatePriorityPost(idPost4, (short)4, author);
                priorityPostModel.updatePriorityPost(idPost5, (short)5, author);
            }     
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    private boolean testIDPost(String idPost){       
        if(idPost.equals(""))
            return false;
        PostModel postModel = PostModel.getInstance();
        PostData postData = postModel.getPostById(idPost);
        if(postData != null)
            return true;
        else 
            return false;
    }
}
